<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "sys_menu".
 *
 * @property int $menuid
 * @property string $menu_code
 * @property string $menu_name
 * @property int $menu_pid
 * @property int $menu_idx
 * @property int $is_show
 * @property string|null $menu_url
 * @property string|null $menu_params
 * @property string|null $menu_icon
 * @property string $menu_status
 * @property int $is_delete
 * @property string $create_at
 * @property string $update_at
 */
class SysMenu extends \yii\db\ActiveRecord
{
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'sys_menu';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['menu_code', 'menu_name'], 'required'],
            [['menu_pid', 'menu_idx', 'is_show', 'is_delete'], 'integer'],
            [['create_at', 'update_at'], 'safe'],
            [['menu_code', 'menu_name', 'menu_status'], 'string', 'max' => 50],
            [['menu_url', 'menu_params', 'menu_icon'], 'string', 'max' => 255],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'menuid' => 'Menuid',
            'menu_code' => 'Menu Code',
            'menu_name' => 'Menu Name',
            'menu_pid' => 'Menu Pid',
            'menu_idx' => 'Menu Idx',
            'is_show' => 'Is Show',
            'menu_url' => 'Menu Url',
            'menu_params' => 'Menu Params',
            'menu_icon' => 'Menu Icon',
            'menu_status' => 'Menu Status',
            'is_delete' => 'Is Delete',
            'create_at' => 'Create At',
            'update_at' => 'Update At',
        ];
    }

    public function getAllMenus()
    {
        $sql = "select * from sys_menu where is_delete=0 and menu_status=:menu_status order by menu_idx";
        return Yii::$app->db->createCommand($sql)
            ->bindValue(':menu_status',"active")
            ->queryAll();
    }

    public function getMenusByRoleids(array $roleids): array
    {
        $sql = "select distinct a.* from sys_menu a inner join sys_role_menu_rela b on a.menuid=b.menuid
                where a.is_delete=0 and b.is_delete=0 and a.menu_status = :menu_status 
                and b.roleid in ( ". implode(',',$roleids).") order by a.menu_idx";
        return Yii::$app->db->createCommand($sql)
                ->bindValue(':menu_status',"active")
                ->queryAll();

    }

    public function conventTree(array $menus, int $menu_pid): array
    {
        $arr_menu_tree = [];
        foreach($menus as $menu)
        {
            if($menu_pid == $menu['menu_pid']){
                $child_menus = $this->conventTree($menus,$menu['menuid']);
                if(!empty($child_menus)){
                    $menu['child_menus'] = $child_menus;
                }
                $arr_menu_tree[] = $menu;
            }
        }

        return $arr_menu_tree;
    }
}
